<?php
/*
 * Copyright (c) 2021.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */


namespace app\common\model\user;

use app\common\model\BaseModel;
use app\common\model\platform\Platform;

/**
 * 用户钱包
 * @package app\common\model\user
 * User: liuhongbin
 * Date: 2021-11-14 23:32
 */
class UserWallet extends BaseModel
{
    public function user()
    {
        return $this->belongsTo(User::class, 'uid', 'uid');
    }

    public function getUseCountAttr($value, $data)
    {
        $Platform = new Platform();
        $mark = $Platform->mark;
        $use_count = $Platform->where(['uid' => $data['uid']])->field("count(*) as count,type")->group('type')->select();
        $res = [
            'wechat' => 0, 'work_wechat' => 0, 'free' => 0, 'douyin' => 0, 'min_app' => 0
        ];
        foreach ($use_count as $key => $value) {
            $type = $mark[$value['type']]??'';
            if($type){
                $res[$type] = $value['count'];
            }
        }
        return $res;
    }

    /**
     * 检查用户平台次数和已使用次数
     * @param $wallet
     * @param $platform_name
     * @return bool
     */
    public function checkWalletPlatformCount($wallet, $platform_name = '')
    {
        if (!$platform_name || !$wallet) {
            return false;
        }
        // 已使用
        $use_count = $wallet['use_count'][$platform_name] ?? 0;
        // 总数
        $count = $wallet[$platform_name] ?? 0;
        return $count > $use_count;
    }
}
